package com.example.dingtalklogin.common.util;

import com.example.dingtalklogin.common.exception.CheckException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;

/**
 * Spring ApplicationContext 工具类
 * @author xuzhen97
 */
@Component
public class SpringUtil implements ApplicationContextAware, ApplicationEventPublisherAware {

    private static ApplicationContext context;
    private static ApplicationEventPublisher eventPublisher;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    /**
     * 获取applicationContext
     * @return
     */
    public static ApplicationContext getContext() {
        if(context == null){
            throw new CheckException("spring context未初始化！");
        }
        return context;
    }

    /**
     * 获取事件发布器
     * @return
     */
    public static ApplicationEventPublisher getEventPublisher(){
        if(eventPublisher == null){
            throw new CheckException("spring context未初始化！");
        }
        return eventPublisher;
    }

    /**
     * 通过name获取 Bean.
     * @param name
     * @return
     */
    public static Object getBean(String name){
        return getContext().getBean(name);
    }

    /**
     * 通过class获取Bean.
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz){
        return getContext().getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz){
        return getContext().getBean(name, clazz);
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        eventPublisher = applicationEventPublisher;
    }
}
